'use strict'

module.exports = angular.module 'libs.interceptors.interceptor', [
  require('authEvents').name
]
.factory 'RequestInterceptor', ($log, $rootScope, $q, AUTH_EVENTS)->
  $log.log "request interceptor init"
  return {
    request: (config)->
      return config
    response: (response)->
      return response
    requestError: (response)->
      return $q.reject(response)
    responseError: (response)->
      if 403 == response.status
        $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated)
      else
        $rootScope.$broadcast("error", response)
      return $q.reject(response)
  }

.factory 'AuthInterceptor', ($log, $rootScope, $q, AUTH_EVENTS)->
  $log.log "auth interceptor init"
  return {
    responseError: (response)->
      $rootScope.$broadcast({
        401: AUTH_EVENTS.notAuthenticated
        403: AUTH_EVENTS.notAuthorized
        419: AUTH_EVENTS.sessionTimeout
        440: AUTH_EVENTS.sessionTimeout
      }[response.status], response)
      return $q.reject(response);
  }
